package com.hsy.linemoney.modules.exchange;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.deparse.dpframe.tools.utils.DPLogUtil;
import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.CalculateService;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.CurrencyService;
import com.hsy.linemoney.apiservice.RecurringService;
import com.hsy.linemoney.apiservice.ServiceTypeService;
import com.hsy.linemoney.modules.common.CommonBaseFragment;
import com.hsy.linemoney.modules.common.HowToSaveDialog;
import com.hsy.linemoney.modules.main.MainActivity;
import com.hsy.linemoney.utils.CommonUtils;

import java.util.Calendar;

/**
 * Created by MartinKent on 2016/7/11.
 */
public class ExchangeMultipleFragment extends CommonBaseFragment implements View.OnClickListener {

    private String[] moneyTypes = {"人民币", "美元", "欧元"};
    private String[] repeatTypes = {"重复类型1", "重复类型2", "重复类型3"};
    private Calendar calendar;

    protected TextView leftPrice;
    protected TextView leftUnit;
    protected TextView rightPrice;
    protected TextView rightUnit;
    protected TextView fromTypeSpinner;
    protected TextView toTypeSpinner;
    protected EditText exchangeAmount;
    protected CheckBox useMarketRate;
    protected EditText expectedRate;
    protected TextView service_type;
    protected TextView repeatTypeSpinner;
    protected TextView startDatePicker;
    protected TextView estimatedAmountPrice;
    protected TextView estimatedAmountUnit;
    protected TextView exechangeCostPrice;
    protected TextView exechangeCostUnit;
    protected TextView bankRate;
    protected TextView weSavedPrice;
    protected TextView weSavedUnit;
    protected TextView howToSave;
    protected TextView nextStep;

    private ViewStub viewStub;
    private boolean isInflated = false;
    private boolean isInflating = false;

    private CurrencyService.CurrencyListResult mCurrencyListResult;
    private int leftWitch = -1, rightWitch = -1;

    private ViewStub.OnInflateListener onInflateListener = new ViewStub.OnInflateListener() {
        @Override
        public void onInflate(ViewStub stub, View inflated) {
            initView(inflated);
            CurrencyService service = new CurrencyService();
            if (service != null) {
                showProgressDialog(getAttchedActivity());
                service.getCurrency(new Callback<CurrencyService.CurrencyListResult>() {
                    @Override
                    public void onSuccess(int what, CurrencyService.CurrencyListResult result) {
                        ExchangeMultipleFragment.this.mCurrencyListResult = result;
                        hideProgressDialog();

                        leftWitch = ((MainActivity) getAttchedActivity()).getExchangeFrom();
                        rightWitch = ((MainActivity) getAttchedActivity()).getExchangeTo();
                        if (-1 != leftWitch && -1 != rightWitch) {
                            fromTypeSpinner.setText(mCurrencyListResult.getCurrency().get(leftWitch).getDescription());
                            toTypeSpinner.setText(mCurrencyListResult.getCurrency().get(rightWitch).getDescription());
                            exchangeAmount.setText(((MainActivity) getAttchedActivity()).getExchangeAmount());
                        } else if (mCurrencyListResult.getCurrency().size() > 1) {
                            leftWitch = 1;
                            rightWitch = 0;
                            fromTypeSpinner.setText(getCurrency(leftWitch).getDescription());
                            toTypeSpinner.setText(getCurrency(rightWitch).getDescription());
                        }
                    }

                    @Override
                    public void onError(int what, int type, String msg, Exception e) {
                        hideProgressDialog();
                    }
                });
            }

            isInflated = true;
        }
    };
    private ViewGroup expectedRateContainer;
    private LinearLayout resultPanel;
    private ViewGroup formContainer;
    private int serviceTypeWhitch = -1;
    private int selectedRecurringTypeWhich = -1;

    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_exchange_multiple;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        showProgressDialog(getAttchedActivity());
        viewStub = findViewById(R.id.view_stub);
        viewStub.setOnInflateListener(onInflateListener);
        inflate(true);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        inflate(isVisibleToUser);
    }

    private void inflate(boolean isVisibleToUser) {
        if (isVisibleToUser && !isInflating && !isInflated) {
            isInflating = true;
            showProgressDialog(getAttchedActivity());
            sendEmptyMessageDelayed(0, 500);
        }
    }

    private CalculateService.CalculateResult mCalculateResult;
    private Runnable mCalcuteRunnable = new Runnable() {
        @Override
        public void run() {
//            showProgressDialog(getAttchedActivity());
            CalculateService service = new CalculateService();
            String source, target;
            source = mCurrencyListResult.getCurrency().get(leftWitch).getCurrencyCd();
            target = mCurrencyListResult.getCurrency().get(rightWitch).getCurrencyCd();
            String send = exchangeAmount.getText().toString();
            send = TextUtils.isEmpty(send) ? "0" : send;
            service.calculate(source, target, send, "0", "ServiceType_101", "0", new Callback<CalculateService.CalculateResult>() {
                @Override
                public void onSuccess(int what, CalculateService.CalculateResult result) {
//                    DecimalFormat df = new DecimalFormat("#.0000");
//                    exchangeAmount.setText(df.format(Double.valueOf(result.getData().getLmData().getLinemoneyPayOut())));
//                    hideProgressDialog();
                    ExchangeMultipleFragment.this.mCalculateResult = result;
                    resultPanel.setVisibility(View.VISIBLE);
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {
                    hideProgressDialog();
                }
            });
        }
    };

    private void initView(View rootView) {
        leftPrice = (TextView) rootView.findViewById(R.id.left_price);
        leftUnit = (TextView) rootView.findViewById(R.id.left_unit);
        rightPrice = (TextView) rootView.findViewById(R.id.right_price);
        rightUnit = (TextView) rootView.findViewById(R.id.right_unit);
        fromTypeSpinner = (TextView) rootView.findViewById(R.id.from_type_spinner);
        fromTypeSpinner.setOnClickListener(ExchangeMultipleFragment.this);
        toTypeSpinner = (TextView) rootView.findViewById(R.id.to_type_spinner);
        toTypeSpinner.setOnClickListener(ExchangeMultipleFragment.this);
        exchangeAmount = (EditText) rootView.findViewById(R.id.exchange_amount);
        useMarketRate = (CheckBox) findViewById(R.id.use_market_rate);
        expectedRate = (EditText) rootView.findViewById(R.id.expected_rate);
        service_type = (TextView) rootView.findViewById(R.id.service_type);
        expectedRateContainer = (ViewGroup) rootView.findViewById(R.id.expected_rate_container);
        repeatTypeSpinner = (TextView) rootView.findViewById(R.id.repeat_type_spinner);
        repeatTypeSpinner.setOnClickListener(ExchangeMultipleFragment.this);
        startDatePicker = (TextView) rootView.findViewById(R.id.start_date_picker);
        startDatePicker.setOnClickListener(ExchangeMultipleFragment.this);
        estimatedAmountPrice = (TextView) rootView.findViewById(R.id.estimated_amount_price);
        estimatedAmountUnit = (TextView) rootView.findViewById(R.id.estimated_amount_unit);
        exechangeCostPrice = (TextView) rootView.findViewById(R.id.exechange_cost_price);
        exechangeCostUnit = (TextView) rootView.findViewById(R.id.exechange_cost_unit);
        bankRate = (TextView) rootView.findViewById(R.id.bank_rate);
        weSavedPrice = (TextView) rootView.findViewById(R.id.we_saved_price);
        weSavedUnit = (TextView) rootView.findViewById(R.id.we_saved_unit);
        howToSave = (TextView) rootView.findViewById(R.id.how_to_save);
        howToSave.setOnClickListener(ExchangeMultipleFragment.this);
        nextStep = (TextView) rootView.findViewById(R.id.next_step);
        nextStep.setOnClickListener(ExchangeMultipleFragment.this);
        resultPanel = (LinearLayout) rootView.findViewById(R.id.result_panel);
        formContainer = (ViewGroup) rootView.findViewById(R.id.form_container);

        service_type.setOnClickListener(this);

        exchangeAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (null == s || 0 == s.length()) {
                    resultPanel.setVisibility(View.GONE);
                } else {
                    mCalculateResult = null;
                    exchangeAmount.removeCallbacks(mCalcuteRunnable);
                    exchangeAmount.post(mCalcuteRunnable);
                }
            }
        });
        useMarketRate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                DPLogUtil.d("onCheckedChanged");
//                expectedRateContainer.setVisibility(isChecked ? View.GONE : View.VISIBLE);
//                formContainer.measure(0, 0);
                expectedRate.setEnabled(!isChecked);
                service_type.setEnabled(!isChecked);
            }
        });

        calendar = Calendar.getInstance();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onHandleMessage(Message message) {
        if (isInflating && !isInflated) {
            viewStub.inflate();
        }
    }

    private String[] currencyArray;

    public String[] getCurrencyArray() {
        if (null == mCurrencyListResult) {
            return null;
        }
        if (null == currencyArray) {
            currencyArray = new String[mCurrencyListResult.getCurrency().size()];
            for (int i = 0; i < currencyArray.length; i++) {
                currencyArray[i] = mCurrencyListResult.getCurrency().get(i).getDescription();
            }
        }
        return currencyArray;
    }

    public CurrencyService.CurrencyListResult.Currency getCurrency(int which) {
        if (null == mCurrencyListResult) {
            return null;
        }
        return mCurrencyListResult.getCurrency().get(which);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.from_type_spinner) {
            CommonUtils.showListDialog(getAttchedActivity(), getCurrencyArray(), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    leftWitch = which;
                    fromTypeSpinner.setText(getCurrencyArray()[which]);
                    dialog.dismiss();
                }
            });
        } else if (view.getId() == R.id.to_type_spinner) {
            CommonUtils.showListDialog(getAttchedActivity(), getCurrencyArray(), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    rightWitch = which;
                    toTypeSpinner.setText(getCurrencyArray()[which]);
                    dialog.dismiss();
                }
            });
        } else if (view.getId() == R.id.repeat_type_spinner) {
            RecurringService service = new RecurringService();
            service.getRecurringType(new Callback<RecurringService.RecurringTypeListResult>() {
                @Override
                public void onSuccess(int what, final RecurringService.RecurringTypeListResult result) {
                    showListDialog(result.getRecurringTypeNameArray(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            selectedRecurringTypeWhich = which;
                            repeatTypeSpinner.setText(result.getRecurringTypeNameArray()[which]);
                            dialog.dismiss();
                        }
                    });
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {

                }
            });
        } else if (view.getId() == R.id.start_date_picker) {
            showDatePicker();
        } else if (view.getId() == R.id.how_to_save) {
            HowToSaveDialog.HowToSaveDialogData data = new HowToSaveDialog.HowToSaveDialogData();
            data.setLinemoneyPayOut(mCalculateResult.getData().getLmData().getLinemoneyPayOut());
            data.setLinemoneyPayOutUnit(toTypeSpinner.getText().toString());
            data.setLinemoneyRate(mCalculateResult.getData().getLmData().getLinemoneyRate());
            data.setLinemoneyTransferFee(mCalculateResult.getData().getLmData().getLinemoneyTransferFee());
            data.setLinemoneyTransferFeeUnit(fromTypeSpinner.getText().toString());

            data.setBankPayOut(mCalculateResult.getData().getBankData().getBankPayOut());
            data.setBankPayOutUnit(toTypeSpinner.getText().toString());
            data.setBankRate(mCalculateResult.getData().getBankData().getBankRate());
            data.setBankTransferFee(mCalculateResult.getData().getBankData().getBankTransferFee());
            data.setBankTransferFeeUnit(fromTypeSpinner.getText().toString());

            new HowToSaveDialog(getActivity(), data).show();
        } else if (view.getId() == R.id.next_step) {
            startActivity(ExchangeStep2Activity.class);
        } else if (view.getId() == R.id.service_type) {
            ServiceTypeService service = new ServiceTypeService();
            service.getServiceTypeList(new Callback<ServiceTypeService.ServiceTypeListResult>() {
                @Override
                public void onSuccess(int what, final ServiceTypeService.ServiceTypeListResult result) {
                    CommonUtils.showListDialog(getAttchedActivity(), R.string.txt_select_service_type, result.getServiceNameArray(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            serviceTypeWhitch = which;
                            service_type.setText(result.getServiceNameArray()[which]);
                            dialog.dismiss();
                        }
                    });
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {

                }
            });
        }
    }

    private void showListDialog(String[] items, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder dialog = null;
        dialog = new AlertDialog.Builder(getContext()).setItems(items, listener);
        dialog.show();
    }

    private void showDatePicker() {
        Dialog dialog = null;

        dialog = new MyDatePicker(getAttchedActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                int month = monthOfYear + 1;
                startDatePicker.setText(year + "-" + month + "-" + dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    private class MyDatePicker extends DatePickerDialog {

        public MyDatePicker(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
            super(context, callBack, year, monthOfYear, dayOfMonth);
        }

        public MyDatePicker(Context context, int theme, OnDateSetListener listener, int year, int monthOfYear, int dayOfMonth) {
            super(context, theme, listener, year, monthOfYear, dayOfMonth);
        }

        @Override
        protected void onStop() {
//            super.onStop();
        }
    }
}
